<template>
  <div class="create-activity-container">
    <div class="content-wrapper">
      <h1>发布活动</h1>
      <el-card class="form-card">
        <el-form ref="activityFormRef" :model="activityForm" :rules="rules" label-width="120px">
          <el-form-item label="活动标题" prop="title">
            <el-input v-model="activityForm.title" placeholder="请输入活动标题" />
          </el-form-item>
          
          <el-form-item label="发布类型" prop="activity_creation_type">
            <el-radio-group v-model="activityForm.activity_creation_type" @change="handleActivityTypeChange">
              <el-radio label="personal">个人发布</el-radio>
              <el-radio label="club">社团发布</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item v-if="activityForm.activity_creation_type === 'club'" label="所属社团" prop="club">
            <el-select v-model="activityForm.club" placeholder="请选择所属社团">
              <el-option v-for="club in userClubs" :key="club.id" :label="club.name" :value="club.id" />
            </el-select>
            <div class="form-hint">只有您作为会长的社团才能发布活动</div>
          </el-form-item>
          
          <el-form-item label="活动类型" prop="activity_type">
            <el-select v-model="activityForm.activity_type" placeholder="请选择活动类型">
              <el-option label="学术讲座" value="academic" />
              <el-option label="文化活动" value="cultural" />
              <el-option label="体育活动" value="sports" />
              <el-option label="志愿活动" value="volunteer" />
              <el-option label="比赛竞赛" value="competition" />
              <el-option label="聚会活动" value="party" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="开始时间" prop="start_time">
            <el-date-picker
              v-model="activityForm.start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
          
          <el-form-item label="结束时间" prop="end_time">
            <el-date-picker
              v-model="activityForm.end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
          
          <el-form-item label="报名截止时间" prop="registration_deadline">
            <el-date-picker
              v-model="activityForm.registration_deadline"
              type="datetime"
              placeholder="选择报名截止时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
          
          <el-form-item label="活动地点" prop="location">
            <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
          </el-form-item>
          
          <el-form-item label="参与人数" prop="max_participants">
            <el-input-number v-model="activityForm.max_participants" :min="1" :max="1000" placeholder="请输入最大参与人数" />
          </el-form-item>
          
          <el-form-item label="活动海报" prop="images">
            <el-upload
              class="image-uploader"
              action="/api/upload/"
              :multiple="true"
              :on-success="handleImageUpload"
              :before-upload="beforeImageUpload"
              :file-list="imageFileList"
            >
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                上传海报
              </el-button>
            </el-upload>
            <div class="upload-hint">支持JPG、PNG格式，建议尺寸1200x800像素，最多上传5张</div>
          </el-form-item>
          
          <el-form-item label="是否免费" prop="is_free">
            <el-switch v-model="activityForm.is_free" />
          </el-form-item>
          
          <el-form-item v-if="!activityForm.is_free" label="活动费用" prop="fee">
            <el-input-number v-model="activityForm.fee" :min="0" :precision="2" placeholder="请输入活动费用" />
          </el-form-item>
          
          <el-form-item label="允许访客" prop="allow_guest">
            <el-switch v-model="activityForm.allow_guest" />
            <div class="form-hint">开启后，非社团成员也可参与活动</div>
          </el-form-item>
          
          <el-form-item label="需要审核" prop="require_approval">
            <el-switch v-model="activityForm.require_approval" />
            <div class="form-hint">开启后，参与者需经审核才能通过报名</div>
          </el-form-item>
          
          <el-form-item label="活动介绍" prop="description">
            <div class="editor-wrapper">
              <!-- 这里简化实现，实际项目中可以使用富文本编辑器 -->
              <el-input v-model="activityForm.description" type="textarea" :rows="8" placeholder="请输入活动详细介绍" />
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm">发布活动</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { activityApi } from '@/api'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

const router = useRouter()
const activityForm = reactive({
  title: '',
  activity_creation_type: 'personal', // 默认个人发布
  club: '',
  activity_type: '',
  start_time: '',
  end_time: '',
  registration_deadline: '',
  location: '',
  max_participants: 50,
  images: [],
  description: '',
  // 布尔字段，设置默认值
  is_free: true,
  fee: 0.00,
  allow_guest: false,
  require_approval: false
})

const imageFileList = ref([])
const userClubs = ref([])

const rules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 100, message: '活动标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  activity_creation_type: [
    { required: true, message: '请选择发布类型', trigger: 'change' }
  ],
  club: [
    {
      required: function() {
        return activityForm.activity_creation_type === 'club';
      }, 
      message: '请选择所属社团', 
      trigger: 'change'
    }
  ],
  activity_type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  registration_deadline: [
    { required: true, message: '请选择报名截止时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' },
    { min: 2, max: 200, message: '活动地点长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  max_participants: [
    { required: true, message: '请输入最大参与人数', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动介绍', trigger: 'blur' },
    { min: 10, max: 5000, message: '活动介绍长度在 10 到 5000 个字符', trigger: 'blur' }
  ]
}

const activityFormRef = ref()

// 获取用户加入的社团
const fetchUserClubs = async () => {
  try {
    // 获取用户社团列表
    const res = await activityApi.getUserClubs()
    if (res && res.data) {
      userClubs.value = res.data
    }
  } catch (error) {
    console.error('获取用户社团失败:', error)
    ElMessage.error('获取社团信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await activityFormRef.value.validate()
    
    // 格式化日期字段，确保符合后端期望的格式 '%Y-%m-%d %H:%M:%S'
    const formattedForm = { ...activityForm }
    
    // 处理时间字段，确保格式正确
    if (formattedForm.start_time) {
      const startTime = new Date(formattedForm.start_time)
      formattedForm.start_time = `${startTime.getFullYear()}-${String(startTime.getMonth() + 1).padStart(2, '0')}-${String(startTime.getDate()).padStart(2, '0')} ${String(startTime.getHours()).padStart(2, '0')}:${String(startTime.getMinutes()).padStart(2, '0')}:00`
    }
    
    if (formattedForm.end_time) {
      const endTime = new Date(formattedForm.end_time)
      formattedForm.end_time = `${endTime.getFullYear()}-${String(endTime.getMonth() + 1).padStart(2, '0')}-${String(endTime.getDate()).padStart(2, '0')} ${String(endTime.getHours()).padStart(2, '0')}:${String(endTime.getMinutes()).padStart(2, '0')}:00`
    }
    
    if (formattedForm.registration_deadline) {
      const deadlineTime = new Date(formattedForm.registration_deadline)
      formattedForm.registration_deadline = `${deadlineTime.getFullYear()}-${String(deadlineTime.getMonth() + 1).padStart(2, '0')}-${String(deadlineTime.getDate()).padStart(2, '0')} ${String(deadlineTime.getHours()).padStart(2, '0')}:${String(deadlineTime.getMinutes()).padStart(2, '0')}:00`
    }
    
    // 创建FormData对象来支持文件上传
    const formData = new FormData()
    
    // 添加所有表单字段到FormData
    for (const key in formattedForm) {
      // 跳过images字段，因为我们会单独处理文件
      if (key !== 'images') {
        formData.append(key, formattedForm[key])
      }
    }
    
    // 添加图片文件到FormData
    // 从imageFileList中获取实际的文件对象
    imageFileList.value.forEach(file => {
      if (file.raw) {
        formData.append('images', file.raw)
      }
    })
    
    // 提交FormData到后端
    const res = await activityApi.createActivity(formData)
    ElMessage.success('活动创建成功！')
    // 跳转到活动详情页
    setTimeout(() => {
      router.push(`/activity/activities/${res.data.id}`)
    }, 1500)
  } catch (error) {
    console.error('发布活动失败:', error)
    // 尝试显示更具体的错误信息
    let errorMessage = '发布失败，请重试'
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMessage = error.response.data.message
      } else if (error.response.data.detail) {
        errorMessage = error.response.data.detail
      }
    }
    ElMessage.error(errorMessage)
  }
}

// 重置表单
// 处理活动类型变化
const handleActivityTypeChange = () => {
  // 切换类型时清空社团选择
  activityForm.club = ''
}

const resetForm = () => {
  activityFormRef.value.resetFields()
  activityForm.images = []
  imageFileList.value = []
}

// 上传前检查
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  const isLessThan5 = activityForm.images.length < 5

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  if (!isLessThan5) {
    ElMessage.error('最多只能上传 5 张图片!')
    return false
  }
  return true
}

// 上传成功处理
const handleImageUpload = (response) => {
  // 假设后端返回图片URL
  if (response && response.data && response.data.url) {
    activityForm.images.push(response.data.url)
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 页面加载时执行
onMounted(() => {
  fetchUserClubs()
})
</script>

<style scoped>
.create-activity-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 20px 0;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.create-activity-container h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.form-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.image-uploader {
  margin-bottom: 10px;
}

.editor-wrapper {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.form-hint,
.upload-hint {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}
</style>